package com.rex.saas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rex.saas.bean.BaseResponse;
import com.rex.saas.bean.DeviceBasicData;
import com.rex.saas.bean.ResultCode;
import com.rex.saas.bean.request.GwRpcRequest;
import com.rex.saas.constants.ApiConstant;
import com.rex.saas.constants.Constants;
import com.rex.saas.service.RexolarApiClient;
import com.rex.saas.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName GwTestController
 * @Description:
 * @Author: zhusiyu
 * @CreateDate: 2024/12/18 10:55	//创建时间
 */
@RestController
@Slf4j
@RequestMapping("/gwTest")
public class GwTestController {
    @Autowired
    private RexolarApiClient rexolarApiClient;

    @RequestMapping("/rpc")
    public BaseResponse rpc(HttpServletRequest httpServletRequest , @RequestBody GwRpcRequest gwRpcRequest) {
        log.info("GwTestController rpc gwRpcRequest:{}", gwRpcRequest);
        String token = httpServletRequest.getHeader("token");
        String tenantId = JwtUtils.getTenantId(token);
        if(StringUtils.isBlank(tenantId)){
            log.error("GwTestController rpc tenantId is null, gwRpcRequest:{}", gwRpcRequest);
            return BaseResponse.error("token异常", ResultCode.PARAM_ERROR);
        }

        if (gwRpcRequest == null || gwRpcRequest.getGatewayId() == null || gwRpcRequest.getFunctionCode() == null || gwRpcRequest.getPayload() == null) {
            log.error("GwTestController rpc gwRpcRequest is null");
            return BaseResponse.error("参数异常", ResultCode.PARAM_ERROR);
        }
        DeviceBasicData gw = rexolarApiClient.getDeviceByDeviceName(gwRpcRequest.getGatewayId(), token);
        if(gw==null){
            log.error("GwTestController rpc gw is null, unbindSubDeviceRequest:{}", gwRpcRequest);
            return BaseResponse.error("设备不存在", ResultCode.PARAM_ERROR);
        }

        JSONObject cmd = new JSONObject();
        try {
            if(gwRpcRequest.getPayload()!=null){
                cmd = JSONObject.parseObject(String.valueOf(gwRpcRequest.getPayload()));
                if(cmd.get("DeviceId")!=null){
                    String deviceName = cmd.get("DeviceId").toString();
                    DeviceBasicData device = rexolarApiClient.getDeviceByDeviceName(deviceName, token);
                    if(device==null){
                        log.error("GwTestController rpc device is null, unbindSubDeviceRequest:{}", gwRpcRequest);
                        return BaseResponse.error("设备不存在", ResultCode.PARAM_ERROR);
                    }
                }
            }
        }catch (Exception e){
            log.error("deviceRpc ILLEGAL_PARAMETERS_JSON_ERROR, deviceRpcRequest:{}", gwRpcRequest, e);
            return BaseResponse.error("payload 格式有误", ResultCode.PARAM_ERROR);
        }


        HashMap dataMap = new HashMap();
        dataMap.put(Constants.Version, "1.0");
        dataMap.put("VendorCode", "Rexense");
        String time = String.valueOf(System.currentTimeMillis());
        dataMap.put("Timestamp", time);
        if(cmd.get("DeviceId")!=null){
            dataMap.put("Seq", cmd.get("DeviceId").toString() + "-" + time);
        }else {
            dataMap.put("Seq", gwRpcRequest.getGatewayId() +"-"+time);
        }
        dataMap.put("DeviceId", gwRpcRequest.getGatewayId());
        dataMap.put("FunctionCode", gwRpcRequest.getFunctionCode());
        dataMap.put("Payload", gwRpcRequest.getPayload());
        boolean flag = rexolarApiClient.updateDeviceAttributes(gw.getCoreId(), ApiConstant.SHARED_SCOPE, JSON.toJSONString(dataMap), token);
        if(flag){
            return BaseResponse.ok();
        }else{
            return BaseResponse.error(ResultCode.SYSTEM_ERROR);
        }
    }
}
